package common;

/**
 * 
 * @author EE orange Clock provide hour, minute, second
 */
public class Clock {
	private boolean is_running = false;
	private int hour = 0, minute = 0, second = 0;

	public Clock() {
		hour = minute = second = 0;
	}

	public Clock(int hour, int minute, int second) {
		if (hour > 0)
			this.hour = hour;
		if (minute > 0)
			this.minute = minute;
		if (second > 0)
			this.second = second;
	}

	/*
	 * 开启时钟
	 */
	public void startClock() {
		if (!is_running) {
			is_running = true;
			Thread thread = new Thread(new ClockThread(this));
			thread.start();
		}
	}

	private class ClockThread implements Runnable {
		Clock clock;

		public ClockThread(Clock clock) {
			this.clock = clock;
		}

		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(1000);
					clock.runStep();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
	}

	public String getTimeString() {
		return String.format("%d:%d:%d", this.getHour(), this.getMinute(), this
				.getSecond());
	}

	public String toString() {
		return this.getTimeString();
	}

	private void runStep() {
		if (++second >= 60) {
			second = 0;
			if (++minute >= 60) {
				minute = 0;
				if (++hour >= 24)
					hour = 0;
			}
		}
	}

	public int getHour() {
		return hour;
	}

	public void setHour(int hour) {
		this.hour = hour;
	}

	public int getMinute() {
		return minute;
	}

	public void setMinute(int minute) {
		this.minute = minute;
	}

	public int getSecond() {
		return second;
	}

	public void setSecond(int second) {
		this.second = second;
	}

}
